<template>
  <div class="edit-container">
    <el-form v-loading="formLoading" ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" maxlength="50" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item label="父级" prop="pid">
            <el-cascader v-model="form.pid" :options="tree" :props="{checkStrictly:true,value:'id',label:'name',children:'childList',emitPath:false}"
               filterable clearable
               :disabled="form.pid==0?true:false"
            >
            </el-cascader>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model.number="form.sort" placeholder="请输入排序"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary" @click="handlerSubmit" v-has-permi="['admin:system:category:save']">保存</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {detail,getTree, save} from "@/api/category";
import {getForm} from "@/utils/utils";

export default {
  props:{
    id:{
      default:null
    },
    pid:{
      default:null
    }
  },
  data(){
    return{
      form:{
        id:null,
        pid:null,
        name:'',
        status:1,
        sort:0,
      },
      rules:{
        name: [{ required: true, message: '请填写姓名', trigger: ['blur'] }],
        sort: [{ required: true, message: '请填写排序', trigger: ['blur'] }]
      },
      tree:[],
      saveLoading:false,
      formLoading:false,
      treeLoading:false,
    }
  },
  mounted() {
    if(this.id){
      this.getDetail();
    }
    this.getTree()
  },
  methods:{
    getTree(){
      this.treeLoading=true
      getTree({keyword:''}).then(res=>{
        if(this.pid){
          this.form.pid=this.pid
        }
        this.tree=res;
      }).finally(()=>{
        this.treeLoading=false
      })
    },
    getDetail(){
      this.formLoading=true
      detail(this.id).then(res=>{
        getForm(res,this.form);
      }).finally(()=>{
        this.formLoading=false;
      })
    },
    handlerSubmit(){
      if(this.saveLoading||this.formLoading||this.treeLoading){
        return;
      }
      this.$refs.form.validate(valid=>{
        if(!valid)return;
        this.saveLoading=true;
        save(this.form).then(()=>{
          this.$message.success('保存成功');
          this.close();
        }).finally(()=>{
          this.saveLoading=false
        })
      })
    },
    close(){
      this.$emit('hideEditDialog')
    }
  }
}
</script>
